package com.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.bo.BargainUserSelect;
import com.xiaobaibai.entity.*;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.*;
import com.xiaobaibai.threadPool.MyThreadPoolUnit;
import com.xiaobaibai.valid.AddGroup;
import com.xiaobaibai.valid.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@Api(tags = "砍价设置接口")
@RequestMapping("/bargain")
@Slf4j
@CrossOrigin
public class BargainController {

    @Autowired
    private IBargainProductService bargainProductService;

    @Autowired
    private IBargainUserService bargainUserService;

    @Autowired
    private IBargainRecordingService bargainRecordingService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IUserService userService;

    /**
     * 1.可砍价商品列表(增删改)
     * 2.砍价列表(点击有详细记录,且可筛选,成功后用户可0.01元下单)
     */
    @GetMapping("/list")
    @ApiOperation("获取可砍价商品列表")//管理端包括未上架的
    public ResponseFormat getBargainList(){

        List<BargainProduct> list = bargainProductService.list();

        return ResponseFormat.ok("获取可砍价商品成功",list);
    }

    @PostMapping("/do-bargain")
    @ApiOperation("增加可砍价商品")
    @CacheEvict(value = "bargain",allEntries = true)
    public ResponseFormat addBargain(@RequestBody @Validated(value = AddGroup.class)
                                                 BargainProduct bargainProduct){
        Product product = productService.getById(bargainProduct.getProductId());
        if(product==null)
            return ResponseFormat.failure("商品id不存在");
        boolean flag = bargainProductService.save(bargainProduct);
        if(!flag)
            return ResponseFormat.failure("增加砍价商品失败");
        return ResponseFormat.ok("增加砍价商品成功",bargainProduct);
    }

    @DeleteMapping("/do-bargain")
    @ApiOperation("删除可砍价商品")
    @CacheEvict(value = "bargain",allEntries = true)
    public ResponseFormat deleteBargain(@RequestParam(value = "id")Integer id){
        BargainProduct bargainProduct = bargainProductService.getById(id);//先查,不然就删没了
        boolean flag = bargainProductService.removeById(id);
        if(!flag)
            return ResponseFormat.failure("删除可砍价商品失败");

        CompletableFuture.runAsync(() -> {
            QueryWrapper<BargainUser> q1=new QueryWrapper<>();
            q1.select("id");
            q1.eq("product_id",bargainProduct.getProductId());
            List<BargainUser> list = bargainUserService.list(q1);//给删除记录用
            if(list!=null&&list.size()!=0)
                bargainRecordingService.removeByBargainUserIdList(list);//删除记录表
        }, MyThreadPoolUnit.threadPoolExecutor);

        CompletableFuture.runAsync(() -> {
            QueryWrapper<BargainUser> q2=new QueryWrapper<>();
            q2.eq("product_id",bargainProduct.getProductId());
            bargainUserService.remove(q2);//删除用户砍价表
        }, MyThreadPoolUnit.threadPoolExecutor);

        return ResponseFormat.ok("删除可砍价商品成功");
    }

    @PutMapping("/do-bargain")
    @ApiOperation("修改可砍价商品")
    @CacheEvict(value = "bargain",allEntries = true)
    public ResponseFormat updateBargain(@RequestBody @Validated(value = UpdateGroup.class)
                                                    BargainProduct bargainProduct){
        boolean flag = bargainProductService.updateById(bargainProduct);
        if(!flag)
            return ResponseFormat.failure("修改砍价商品失败");
        return ResponseFormat.ok("修改砍价商品成功");
    }

    @PostMapping("/user-bargain-list")
    @ApiOperation("用户砍价列表")//后台实现分页+过滤排序
    public ResponseFormat getUserBargainList(@RequestBody BargainUserSelect bargainUserSelect){
        /**
         * 1.筛选条件->状态+商品id+用户id
         * 2.排序条件->进度单位
         * 3.默认顺序->所有的并且按照id来排序
         */
        bargainUserSelect.setPageNum(bargainUserSelect.getPageNum()-1);//适配减一
        List<BargainUser> list = bargainUserService.getUserBargainList(bargainUserSelect);
        int count=bargainUserService.count();
        Map<String,Object> map=new HashMap<>();
        map.put("data",list);
        map.put("total",count);
        return ResponseFormat.ok("获取用户砍价列表成功",map);
    }

    @GetMapping("/user-bargain-detail")
    @ApiOperation("根据砍价用户查出它的砍价记录")
    public ResponseFormat getUserBargainDetail(@RequestParam(value = "bargainId")Integer bargainId,
                                               @RequestParam(value = "userId")Integer userId,
                                               @RequestParam(value = "productId")Integer productId) throws ExecutionException, InterruptedException {
        Map<String,Object> map=new HashMap<>();

        CompletableFuture<Void> c1 = CompletableFuture.runAsync(() -> {
            QueryWrapper<Product> q2 = new QueryWrapper<>();
            q2.select("id", "product_name", "product_image", "product_price");
            q2.eq("id", productId);
            Product product = productService.getOne(q2);
            map.put("product", product);
        }, MyThreadPoolUnit.threadPoolExecutor);

        CompletableFuture<Void> c2 = CompletableFuture.runAsync(() -> {
            QueryWrapper<User> q1 = new QueryWrapper<>();
            q1.select("user_id", "user_name", "user_image", "user_gender");
            q1.eq("user_id", userId);
            User user = userService.getOne(q1);
            map.put("user", user);
        }, MyThreadPoolUnit.threadPoolExecutor);

        QueryWrapper<BargainRecording> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("bargain_user_id",bargainId);
        List<BargainRecording> list = bargainRecordingService.list(queryWrapper);
        map.put("detail",list);

        CompletableFuture<Void> all = CompletableFuture.allOf(c1, c2);
        all.get();//等待

        return ResponseFormat.ok("查询砍价用户详细信息成功",map);
    }

}
